package com.scott;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Scott 2017/11/30 08:20
 */
public class TestDemo {

    private static List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

    private static AtomicInteger result = new AtomicInteger();

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        pool.invoke(new addTask(result, list));
        System.out.println(result.get());
    }

    private static class addTask extends RecursiveAction {

        private AtomicInteger tmp;

        private List<Integer> toComputeList;

        public addTask(AtomicInteger result, List<Integer> toComputeList) {
            this.tmp = result;
            this.toComputeList = toComputeList;
        }

        @Override
        protected void compute() {
            int size = toComputeList.size();
            if (size > 1) {
                List<Integer> leftList = toComputeList.subList(0, size / 2);
                List<Integer> rightList = toComputeList.subList(size / 2, size);
                invokeAll(new addTask(tmp, leftList), new addTask(tmp, rightList));
            } else {
                if (size == 1) {
                    while (!tmp.compareAndSet(tmp.get(), tmp.get() + toComputeList.get(0))) {
                        System.out.println("添加成功");
                    }
                }
            }

        }
    }
}
